package pl.edu.mimuw.mas.agent.behaviour.helicopter.verification;

import java.io.IOException;

import jade.core.behaviours.OneShotBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pl.edu.mimuw.mas.agent.HelicopterAgent;
import pl.edu.mimuw.mas.message.PositionMessage;

/**
 * Zachowanie rozyłające zapytania o weryfikację łosia.
 */
public class SendCfpBehaviour extends OneShotBehaviour {
	private static final long serialVersionUID = 7320063351337425137L;
	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	public SendCfpBehaviour(HelicopterAgent agent) {
		super(agent);
	}
	
	public void action() {
		HelicopterAgent ha = (HelicopterAgent) myAgent;
		
		ACLMessage msg = new ACLMessage(ACLMessage.CFP);
		try {
			msg.setContentObject(new PositionMessage(ha.getAID(), ha.getPosition()));
			msg.setConversationId(HelicopterAgent.HELICOPTER_VERIFY_CONV);
		} catch (IOException e) {
			logger.error("{}: błąd serializacji", myAgent.getName(), e);
		}
		
		DFAgentDescription template = new DFAgentDescription();
  		ServiceDescription sd = new ServiceDescription();
  		sd.setType(HelicopterAgent.SERVICE_TYPE);
  		template.addServices(sd);
  		  		
		try {
			DFAgentDescription[] results = DFService.search(myAgent, template);
			for (int i = 0; i < results.length; i++) {
	  			msg.addReceiver(results[i].getName());
	  		}
		} catch (FIPAException e) {
			logger.error("{} : błąd FIPA", myAgent.getName(), e);
		}
		
		myAgent.send(msg);
	}
}
